package edu.berkeley.cs160.innovationers.shoppersidekick;

import java.util.ArrayList;

import edu.berkeley.cs160.innovationers.shoppersidekick.database.MyDB;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class MemberList extends Activity {
	private ArrayList<Member> MemberList;
	private MemberAdapter memAdapter;
	private myApp appInfo;
	MyDB localDatabase;
	ArrayList<Member> localFromDatabase;
	MemberList x;
	
    @Override
	public void onActivityResult(int requestCode,int resultCode,final Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch(requestCode) {
			case 100: 
				if(resultCode == 100){
				Member temp = new Member();
				temp.setName(data.getCharSequenceExtra("CONTENT").toString());
				MemberList.add(0,temp);
				if(!appInfo.getLocalMemberList().contains(temp))
					appInfo.getLocalMemberList().add(temp);
				localDatabase.insertdiary(data.getCharSequenceExtra("CONTENT").toString(), "999", "M");
	        	memAdapter.notifyDataSetChanged();
				}
		}
		hint();
	}
    
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK){
        	Intent intent = new Intent();
        	appInfo.setMemberList(MemberList);
        	setResult(myApp.memberChanged,intent);
        	localDatabase.close();
        	finish();
        }
		return super.onKeyUp(keyCode, event);
    }
    

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.memberlist);
        setTitle("Edit Members");
        Log.v("member","1");
        localDatabase = new MyDB(this);
        localDatabase.open();
        Log.v("member","2");
        x = this;
        
        appInfo = (myApp) getApplication();
        
        MemberList = appInfo.getMemberList();
        if(appInfo.isCheckList())
        	memAdapter = new myMemberCheckAdapter(this, MemberList);
        else
        	memAdapter = new myMemberAdapter(this, MemberList);
        
        localFromDatabase = appInfo.getLocalMemberList();
        Cursor c = localDatabase.getMembersFromList(appInfo.getShoppingList().get(appInfo.getPosition()).getName());
        Log.v("ADD FROM DATA", "1");
        if(c.moveToFirst()){
        	do{
        		String itemName2, quantity2, listName2;
    			itemName2 = c.getString(c.getColumnIndex(Constants.ITEM_NAME));
    			listName2 = c.getString(c.getColumnIndex(Constants.LIST_NAME));
    			
    			Log.v("ADD FROM DATA", itemName2);
    			
    			Member temp = new Member();
    			temp.setName(itemName2);
    			localFromDatabase.add(temp);
        		
        	}while(c.moveToNext());
        }
        
        
        ListView memberView = (ListView) findViewById(R.id.MemberListView);
        memberView.setAdapter(memAdapter);
        memberView.setTextFilterEnabled(true);
        memberView.setSmoothScrollbarEnabled(true);
        
        Button addButton = (Button) findViewById(R.id.addMemberBotton);
        addButton.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				Intent myIntent = new Intent(MemberList.this, AddMember.class);
        		startActivityForResult(myIntent,100);
			}

        });
        
        Button backButton = (Button) findViewById(R.id.backFromMemberList);
        backButton.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
            	appInfo.setMemberList(MemberList);
            	setResult(myApp.memberChanged,intent);
            	localDatabase.close();
            	finish();
			}

        });
        
        hint();
    }
    
    private class myMemberAdapter extends MemberAdapter{

		public myMemberAdapter(Context context, ArrayList<Member> mem) {
			super(context, mem);
		}
		@Override
		public View getView(final int position, View convertView, ViewGroup parent){
			LinearLayout MemberListLayout;
			final Member member = MemberList.get(position);
			MemberListLayout = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.memberlistelement, parent, false);
			TextView memName = (TextView) MemberListLayout.findViewById(R.id.MemberName);
			memName.setText(member.getName());
			ImageView memPic = (ImageView) MemberListLayout.findViewById(R.id.MemberPic);
			memPic.setImageResource(R.drawable.default_large);
			Button delMember = (Button) MemberListLayout.findViewById(R.id.MemberDel);
			delMember.setOnClickListener(new OnClickListener(){
	        	public void onClick(View view){
	        		AlertDialog alertDialog = new AlertDialog.Builder(MemberList.this).create();
	        		
	        		alertDialog.setTitle("Delete Member");
	        		alertDialog.setMessage("Delete Member "+member.getName()+"?");
	        		alertDialog.setButton(alertDialog.BUTTON_POSITIVE,"OK", new DialogInterface.OnClickListener() {
	        		   public void onClick(DialogInterface dialog, int which) {
	        			   MemberList.remove(member);
	        			   localDatabase.deleteMember(member.getName());
	   	        		   memAdapter.notifyDataSetChanged();
	        		   }
	        		});
	        		
	        		alertDialog.setButton(alertDialog.BUTTON_NEGATIVE,"Cancel", new DialogInterface.OnClickListener() {
		        		   public void onClick(DialogInterface dialog, int which) {

		        		   }
		        	});

	        		alertDialog.show();
	        		
	        		
	        	}
	        });
			return MemberListLayout;
		}
    }
    
    private class myMemberCheckAdapter extends MemberAdapter{

		public myMemberCheckAdapter(Context context, ArrayList<Member> mem) {
			super(context, mem);
		}
		@Override
		public View getView(final int position, View convertView, ViewGroup parent){
			LinearLayout MemberListLayout;
			final Member member = MemberList.get(position);
			MemberListLayout = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.memberlistelementcheck, parent, false);
			TextView memName = (TextView) MemberListLayout.findViewById(R.id.MemberName);
			memName.setText(member.getName());
			ImageView memPic = (ImageView) MemberListLayout.findViewById(R.id.MemberPic);
			memPic.setImageResource(R.drawable.default_large);
			final CheckBox checkMember = (CheckBox) MemberListLayout.findViewById(R.id.MemberCheckbox);
			
			if(x.checkMember(member))
				checkMember.setChecked(true);
			
			checkMember.setOnClickListener(new OnClickListener(){
	        	public void onClick(View view){
	        		ArrayList<Member> local= localFromDatabase;//appInfo.getLocalMemberList();
	        		
	        		 if(checkMember.isChecked()){
	        			 if(!local.contains(member))
	        				 {local.add(member);
	        				 Log.v("ADD", "ADD");
	        				 localDatabase.insertdiary(member.getName(), "999", appInfo.getShoppingList().get(appInfo.getPosition()).getName());
	        				 }
	        		 }else
	        			 if(local.contains(member))
	        				 {
	        				 
	        				 local.remove(member);
	        				 Log.v("REMOVE", "REMOVE");
	        				 localDatabase.deleteMemberFromList(member.getName(), appInfo.getShoppingList().get(appInfo.getPosition()).getName());
	        				 
	        				 }
	        	}
	        });
			return MemberListLayout;
		}
    }
    
    private void hint(){
    	TextView temp = (TextView) findViewById(R.id.memview_hint);
    	
        if(MemberList.size() < 1){
        	if(appInfo.isCheckList())
        		temp.setText("Use 'add' to add a friend you want to share this shopping list with. Use the check box to uncheck the member you don't want to synchronize this list with");
        	else
        		temp.setText("Use 'add' to add a friend you want to be part of this shopping app. Use the 'x' button to remove them.");
        	temp.setTextSize(15);
        	temp.setTextColor(Color.GRAY);
        }else{
        	temp.setText("");
        }
    }
    public boolean checkMember(Member m){
    	int i;
    	i=0;
    	int x = localFromDatabase.size();
    	if(x != 0)
    	while(i<x && localFromDatabase.get(i) != null){
    	if
    	(localFromDatabase.get(i).getName().equals(m.getName()))
    		return true;
    	
    	i = i + 1;
    	}
    	
    	return false;
    	
    }
}